<?php
namespace control;
// 消息提醒设置
class reminderSettingClass extends adIndexClass
{
    private const page = 'reminderSetting';
    private const table = 'reminder_settings';
    private const title = '消息提醒设置';

    /*编码入口页*/
    public function home(): string
    {
        $type = $this->get('type') ?: '行政';
        $all = $this->getPowerAll();
        //返回
        $rightHtml = $this->homeRight();
        $html =  componentClass::leftNav([
            'title'=>'分类',
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        $html .= <<<EOT
<script>
function replaceRightDetail(obj, cla = '{$this->get('cla')}') {
     let api, id = $(obj).attr('data-id')
    if (id.length > 0) {
        let that = $(obj).parent('ul')
        const two = that.attr('pid');
        const one = that.parent('ul').attr('pid');
        // ulScal(obj, id)
        $('#container-left').find('li').removeClass('active')
        $(obj).addClass('active')
        api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson'
        $.post(api, {
            menuOne:one,
            menuTwo: two,
            menuThree: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}
 function cancelPage(id){
    if (id){
       let obj =  $("[data-id='"+id+"']");
        replaceRightDetail(obj,'reminderSetting'); 
    }
}
 $(function (){
     cancelPage('{$type}')
 })
</script>
EOT;
        //返回
        return $this->homeFun($html);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "消息ID" => text(array("name" => "id")).
                        hidden(['name' => 'menuThree', 'value' => $this->post('menuThree')]),
                    "类型"   => select(["name" => "type", 'option' => ['提醒消息', '预警消息']]),
                    '对象' => text(array('name' => 'name')),
                ],
                [
                    '发送条件'  => text(array('name' => 'conditions')),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function homeRight(): string
    {
        $html = $this->homeOptions(false);
        $button = "";
        return $this->search($html, layout: 'pop', toolButton: $button);
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $json['html'] = $this->getPowerAll();
        return json_encode($json, 320);
    }

    /**
     * 获取数据
     *
     * @return array
     */
    private function orginalData(): array
    {
        return [
            '行政',
            '销售',
            '采购',
            '委外',
            '物流',
            '库存',
            '核算',
            '生产',
            '质量',
            '往来账/出纳',
            '总账',
        ];
    }

    public function getPowerAll(array $local = [], string $pid = ''): string
    {
        $result = $local ?: $this->orginalData();
        $style = empty($pid) ? 'pid=0' : ' class="child-node"';
        $temp = "<ul $style $pid>";
        // 角标
        $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
        $lastone = lastone;
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        foreach ($result as $key => $value) {
            // 判断下级是否存在
            $pid = "pid=$value";
            if (is_array($value)) {
                $temp .= "<li data-id='$key' onclick=\"replaceRightDetail(this)\">$arrow <span class='textcontent'>{$textcontent_ico}{$key}</span></li>";
                $temp .= $this->getPowerAll($value, $pid);
            } else {
                $temp .= "<li data-id='$value' onclick=\"replaceRightDetail(this)\">$lastone <span class='textcontent'>{$textcontent_ico}{$value}</span></li>";
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 异步加载
     */
    public function homeRightJson(): string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): string
    {
        return $this->homeSearch();
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'id'          => [
                        'name'  => "消息ID",
                        'width' => 150,
                    ],
                    'type'  => [
                        'name'  => '类型',
                        'width' => 100,
                    ],
                    'name'         => [
                        'name'  => '对象',
                        'width' => 150,
                    ],
                    'selector'          => [
                        'name'  => '接收人',
                        'width' => 100,
                    ],
                    'conditions'          => [
                        'name'  => '发送条件',
                        'width' => 200,
                    ],
                    'field_name'          => [
                        'name'  => '条件参数ID',
                        'width' => 150,
                    ],
                    'threshold'          => [
                        'name'  => '条件与阈值',
                        'width' => 100,
                    ],
                    'list'          => [
                        'name'  => '排序号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'updateTime'          => [
                        'name'  => '更新时间',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询结果*/
    public function homeSearch(): bool|string
    {
        $menuThree = $this->post('menuThree');
        $and = " and classify = '$menuThree'";
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//对象
            "conditions" => $this->post('conditions'),//条件
        );
        //全等查询数组
        $equal = array(
            "id" => $this->post('id'),//ID
            "type" => $this->post('type'),//类型
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "layer('" . self::page . "','edit',{id:'".$array['id']."'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'selector':
                        $row[] = checkPlanClass::showSelectorText($array['selector']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] ."<form name='trainRecordForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $html = $this->layerEdit(array("table" => array(
            array(
                "消息类型：" => $info['type'],
            ),
            array(
                "消息对象：" => $info['name'],
            ),
            array(
                must."接收人：" => componentClass::staffSelector($info['selector']),
            ),
            array(
                "发送条件：" => $info['conditions']
            ),
            array(
                "条件阈值：" => text(array('name' => 'threshold', 'class' => 'text', 'value' => $info['threshold'])),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑",'winFix'=>true, "height" => 470, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'selector'       => $this->post('staff')[0]??'',//员工选择器
            'threshold' => $this->post('threshold')
        ];
        $field['member'] = implode(',',componentClass::returnStaffId($field['selector']));
        $annotation = [
            'selector' => '接收人',
        ];
        $rules = [
            'selector' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $json['warn'] = "对应消息不存在";
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

}
